﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Configuration;
using System.Web.Security;
using GMAC.ReportingSystem.Business.Entities;
using Components = GMAC.ReportingSystem.Business.Components;

namespace GMAC.ReportingSystem
{
    public partial class Login : System.Web.UI.Page
    {
        #region Page Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;
            if (User.Identity.IsAuthenticated && Session["User"] != null)
            {
                Success(Session["User"] as  User);
            }


            ////TODO: QUITAR ESTAS LÍNEAS. Solo estan para no tener que ingresar login en cada prueba
            //rfvLogin.Enabled = false;
            //rfvPassword.Enabled = false;
        }

        #endregion

        #region Button Events

        protected void imgEnterSite_Click(object sender, ImageClickEventArgs e)
        {
            var uc = new Components.UserComponent();

            //TODO: QUITAR ESTAS LÍNEAS. Solo estan para no tener que ingresar login en cada prueba
            var user = new User();//= uc.Login("admin", "123456789"/*txtLogin.Text, txtPassword.Text*/);
            //if (txtLogin.Text == "")
            //{
            //    user = uc.Login("admin", "123456789");
            //}
            //else 
            //{
            user = uc.Login(txtLogin.Text, txtPassword.Text);
            //}

            if (user != null)
            {
                Success(user);
            }
            else
            {
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The user couldn't be authenticated. Verify your login and password.", null);
                popupExtenderMessage.Show();
                btnAccept.Focus();
            }
        }
        protected void btnForgotPassword_Click(object sender, ImageClickEventArgs e)
        {
            if (string.IsNullOrEmpty(txtLogin.Text))
            {
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The login user must not be empty.", null);
                popupExtenderMessage.Show();
                txtLogin.Focus();
            }
            else
            {
                var mail = new FrameworkManapro.Mail.Mail
                {

                    Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["userMail"],
                                                                   ConfigurationManager.AppSettings["userMailPassword"], ConfigurationManager.AppSettings["domainMail"]),
                    Body = BuildMail(),
                    Subject = ConfigurationManager.AppSettings["subjectMail"],
                    From = ConfigurationManager.AppSettings["mailFrom"],
                    IsBodyHtml = true,
                    To = ConfigurationManager.AppSettings["adminEmail"],
                    Host = ConfigurationManager.AppSettings["smtpAddress"],
                    Port = int.Parse(ConfigurationManager.AppSettings["smtpPort"])
                };
                if (mail.Body != null)
                {
                    mail.SendMail(mail.CreateMail(), mail.SmtpMail());
                    wucMessage.ShowMessage(UserControls.MessageType.Success, "Your password has been sent successfully.", null);
                    popupExtenderMessage.Show();
                }

            }

        }

        #endregion

        #region Other Events

        #endregion

        #region Private Methods

        protected void Success(User user)
        {

            //FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(user.Login, false, 30);
            //string encryptedTicket = FormsAuthentication.Encrypt(ticket);
            //HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            //Response.Cookies.Add(authCookie);
            Session["User"] = user;
            FormsAuthentication.SetAuthCookie(user.Login, false);
            FormsAuthentication.RedirectFromLoginPage(user.Login, false);
            //Response.Redirect("ChangePassword.aspx");
            //Response.Redirect(FormsAuthentication.DefaultUrl);
        }

        protected string BuildMail()
        {
            var bcUser = new Components.UserComponent();
            var beUser = bcUser.GetByLogin(txtLogin.Text);
            var sb = new StringBuilder();
            if (beUser == null)
            {
                wucMessage.ShowMessage(UserControls.MessageType.Error, "Login is not registered", null);
                popupExtenderMessage.Show();
                txtLogin.Focus();
            }
            else
            {

                sb.Append("<html><body>");

                sb.Append("<table>");

                sb.Append("<tr>");

                sb.Append("<td style='width: 100%' colspan='3'><span style='font-family: Helvetica, Arial, MS Sans Serif; font-size: 16px; font-style: normal;font-weight: bold;'>");

                sb.Append("Correo Automático Enviado por el Sistema Direct Debit");

                sb.Append("</span></td></tr>");

                sb.Append("<tr><td style='width: 100%; height: 20px' colspan='3'></td></tr><tr><td style='width: 100%' colspan='3'>");

                sb.Append("<span style='font-family: Helvetica, Arial, MS Sans Serif; font-size: 12px; font-style: normal;font-weight: bold;'>");

                sb.Append("El Usuario " + beUser.Login.ToString() + " Olvidó la contraseña. Requiere ser Reiniciada por el Administrador del Sistema");

                sb.Append("</span></td></tr></ br>");

                sb.Append("<tr><td style='width: 100%' colspan='3'><span style='font-family: Helvetica, Arial, MS Sans Serif; font-size: 12px; font-style: normal;font-weight: bold; text-decoration: underline'>");

                sb.Append("Datos del Usuario:</span></td></tr><tr><td style='width: 2%'></td>");

                sb.Append("<td style='width: 1%; vertical-align: middle'>");

                sb.Append("<span style='font-family: Helvetica, Arial, MS Sans Serif; font-size: 12px; font-style: normal;vertical-align: middle'>1.-</span></td>");

                sb.Append("<td style='width: 100%'><span style='font-family: Helvetica, Arial, MS Sans Serif; font-size: 12px; font-style: normal;'>");

                sb.Append("<b>Nombre y Apellido: </b>" + beUser.FullName.ToString() + "</span></td></tr>");

                sb.Append("<tr><td style='width: 2%'></td><td style='width: 1%; vertical-align: middle'>");

                sb.Append("<span style='font-family: Helvetica, Arial, MS Sans Serif; font-size: 12px; font-style: normal;vertical-align: middle'>2.-</span>");

                sb.Append("</td><td style='width: 100%'><span style='font-family: Helvetica, Arial, MS Sans Serif; font-size: 12px; font-style: normal;'>");

                sb.Append("<b>Cédula: </b>" + beUser.IdentificationNumber.ToString() + "</span></td></tr>");

                sb.Append("<tr><td style='width: 2%'></td><td style='width: 1%; vertical-align: middle'>");

                sb.Append("<span style='font-family: Helvetica, Arial, MS Sans Serif; font-size: 12px; font-style: normal;vertical-align: middle'>3.-</span></td>");

                sb.Append("<td style='width: 100%'><span style='font-family: Helvetica, Arial, MS Sans Serif; font-size: 12px; font-style: normal;'>");

                sb.Append("<b>Correo: </b>" + beUser.Email.ToString() + "</span></td></tr>");

                sb.Append("<tr><td style='width: 2%'></td><td style='width: 1%; vertical-align: middle'>");

                sb.Append("<span style='font-family: Helvetica, Arial, MS Sans Serif; font-size: 12px; font-style: normal;vertical-align: middle'>4.-</span></td>");

                sb.Append("<td style='width: 100%'><span style='font-family: Helvetica, Arial, MS Sans Serif; font-size: 12px; font-style: normal;'>");

                sb.Append("<b>Departamento: </b>" + beUser.Department.ToString() + "</span></td></tr>");

                sb.Append("<tr><td style='width: 2%'></td><td style='width: 1%; vertical-align: middle'>");

                sb.Append("<span style='font-family: Helvetica, Arial, MS Sans Serif; font-size: 12px; font-style: normal;vertical-align: middle'>5.-</span></td>");

                sb.Append("<td style='width: 100%'><span style='font-family: Helvetica, Arial, MS Sans Serif; font-size: 12px; font-style: normal;'>");

                sb.Append("<b>Grupo al que Pertenece: </b>" + beUser.Role.Name + "</span></td></tr>");

                sb.Append("<tr><td style='width: 100%; height: 30px' colspan='3'></td></tr>");

                sb.Append("<tr><td style='width: 100%' colspan='3'><span style='font-family: Helvetica, Arial, MS Sans Serif; font-size: 10px; color: Gray;font-style: normal;'>");

                sb.Append("Nota: Este correo es informativo. No responda ni reenvíe la información que aquí se sumnistra.</span>");

                sb.Append("<br /><span style='font-family: Helvetica, Arial, MS Sans Serif; font-size: 10px; color: Gray;font-style: normal; font-weight: bold'>");

                sb.Append("<b>Este correo es CONFIDENCIAL.</b></span></td></tr></table></body></html>");





                return sb.ToString();
            }
            return null;
        }

        #endregion
    }
}
